import { Selection } from '@antv/x6-plugin-selection'
import Nifi from '../nifi'
import { ref } from 'vue'
import { IPackNifi } from 'src/inter';
import { getCamelName } from "../util"
import { ElMessage } from 'element-plus';
import {t} from "../i18n/index"

export default (nifi: Nifi) => {

    // 已选的 cell 集合
    const cells = new Set<string>();
    // 已选的 edge 集合
    const edges = new Set<string>();
    // 已选的 节点 集合
    const nodes = new Set<string>();
    //
    const selectCount = ref(0)
    const copyCount = ref(0)
    //
    let snippet: any = { parentGroupId: '', connections: {}, funnels: {}, inputPorts: {}, labels: {}, outputPorts: {}, processGroups: {}, processors: {}, remoteProcessGroups: {} }
    //
    // 清空已选
    const clear = () => {
        console.log('clear=============')
        cells.clear();
        edges.clear();
        nodes.clear();
        selectCount.value = 0;
        copyCount.value = 0;
        snippet = { parentGroupId: '', connections: {}, funnels: {}, inputPorts: {}, labels: {}, outputPorts: {}, processGroups: {}, processors: {}, remoteProcessGroups: {} };
    }
    // 框选的配置数据
    const config: Selection.Options = {
        className: "graph-cell-selected",
        enabled: true,
        multiple: true,
        rubberband: true,
        movable: true,
        strict: true,
        showNodeSelectionBox: false,
        showEdgeSelectionBox: false,
        // content:"aaaaaaaaaa",
        pointerEvents: "none",
        multipleSelectionModifiers: ["ctrl"],
        modifiers: ["ctrl"]
    }

    nifi.graph.onMounted((graph) => {
        graph.use(new Selection(config))
        //
        graph.on("selection:changed", ({ selected, options }: { selected: any[], options: any }) => {
            console.log('selection:changed -----------',selected)
            clear();
            //
            for (const e of selected) {
                const id = e.id;
                cells.add(id)
                if (e.isNode()) {
                    nodes.add(id)
                }
                else {
                    edges.add(id)
                }
            }
            // 当非框选模式或者 框选的节点数小于 2 的时候直接返回，不进行后续处理
            if (options.batch && nodes.size > 1) {
                // 解决框选无法选中边的问题
                const es = graph.getEdges();
                for (const e of es) {
                    const id = e.id;
                    const sid = e.getSourceCellId();
                    const tid = e.getTargetCellId();
                    if (nodes.has(sid) && nodes.has(tid)) {
                        edges.add(id);
                        cells.add(id);
                        // 框选模式下 追加边的选中状态
                        graph.select(e)
                    }
                }
            }
            //
            selectCount.value = cells.size;
        })

        graph.on('blank:click', () => {
            console.log('blank:click -----------')
            clear();
        })
    })
    // 选择 | 全选
    const select = (cells?: IPackNifi.SC[] | IPackNifi.SC) => {
        let cs = cells;
        if (cs == undefined) {
            cs = nifi.graph?.getCells() || [];
        }
        //
        nifi.graph?.select(cs)
    }
    // 反选
    const inverse = () => {
        const cs = nifi.graph?.getSelectedCells() || [];
        const es = nifi.graph?.getCells() || [];
        //
        const cells = es.filter(e => !cs.includes(e));
        nifi.graph?.resetSelection(cells)
    }
    // 初始化切片数据
    const initSnippet = () => {
        let ct = 0;
        for (const id of cells) {
            const e = nifi.graph?.getCellById(id);
            if (e) {
                const sv = { clientId: nifi.flow.clientId, version: e.prop('version') };
                const name = getCamelName(e)
                snippet[name][id] = sv;
                ct++;
            }
        }
        if (ct > 0) {
            snippet.parentGroupId = nifi.group.id;
        }
        return ct;
    }
    // 复制
    const copy = (cell?:IPackNifi.SC) => {
        if(cell){
            clear();
            cells.add(typeof cell == 'string' ? cell : cell.id)
        }
        copyCount.value = initSnippet();
    }
    // 创建切片
    const newSnippet = async () => {
        // 创建切片
        const url = '/nifi-api/snippets'
        try {
            const res = await nifi.api.post(url, { disconnectedNodeAcknowledged: false, snippet })
            return res.snippet.id as string;
        } catch (error) {
            ElMessage.error(t('useselect-new-snippet-failed',{error}))
            return false;
        }
    }

    // 粘贴
    const paster = async (e: { x: number, y: number }) => {
        if (copyCount.value == 0) { ElMessage.warning(t('useselect-put-snippet-warn')) }
        const snippetId = await newSnippet();
        if (snippetId === false) return;
        // 放置切片到当前位置
        const url = `/nifi-api/process-groups/${nifi.group.id}/snippet-instance`
        try {
            const res = await nifi.api.post(url, { disconnectedNodeAcknowledged: false, originX: e.x, originY: e.y, snippetId })
            // 渲染复制的节点
            if (res.flow) {
                // 增量渲染
                nifi.group.add(res.flow)
            }
        } catch (error) {
            ElMessage.error(t('useselect-put-snippet-failed',{error}))
        }
    }

    // 批量删除
    const batchDelete = async () => {
        if (selectCount.value == 0) { ElMessage.warning(t('useselect-del-snippet-warn')) }
        initSnippet();
        const snippetId = await newSnippet();
        if (snippetId === false) return;
        // 删除切片
        const url = `/nifi-api/snippets/${snippetId}?disconnectedNodeAcknowledged=false`;
        try {
            await nifi.api.delete(url)
        } catch (error) {
            ElMessage.error(t('useselect-del-snippet-failed',{error}))
            return;
        }
        // 刷新画布
        nifi.group.refresh();
    }


    return { cells, edges, nodes, snippet, selectCount, copyCount, copy, paster, clear, select, inverse, batchDelete }

}